/**
 * 全局自定义 api签名合法校验
 * @params {object} koa 实例
 */

const md5 = require('md5');

module.exports = (app) => {
    return async (ctx, next) => {
        // 只对api校验
        if (ctx.path.indexOf('/api') < 0) {
            return await next();
        }

        const { method, path } = ctx;
        const { headers } = ctx.request;
        const { s_sign: sSgin, s_t: st } = headers;

        const signKey = 'zylwin_12345';
        const signature = md5(`${signKey}_${st}`);
        app.logger.info(`[${method} ${path}] signature: ${signature}`);

        if (!sSgin || !st || signature != sSgin.toLowerCase() || Date.now() - st > 1000 * 30) {
            ctx.status = 200;
            ctx.body = {
                success: false,
                msg: 'signature is error !',
                code: 445
            }
            return
        }

        await next();
    }
}